package com.autumn.mybatis.factory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.sql.DataSource;

import com.autumn.mybatis.provider.IDbProvider;
import com.autumn.util.ExceptionUtils;

/**
 * 基于路油 Key 动态数据源
 * 
 * @author 老码农
 *
 *         2018-01-10 16:38:15
 */
public abstract class AbstractDynamicRoutingKeyDataSource extends AbstractDynamicRoutingDataSource
		implements IDynamicDataSourceRouting {

	private final Map<String, DataSource> targetDataSources;

	public AbstractDynamicRoutingKeyDataSource(IDataSourceFactory dataSourceFactory, IDbProvider provider) {
		super(dataSourceFactory, provider);
		this.targetDataSources = new ConcurrentHashMap<>();
	}

	@Override
	protected final DataSource getCurrentDataSource() {		
		return this.targetDataSources.computeIfAbsent(this.getRoutingKey(), (key) -> {
			DataSource ds = this.getDataSourceFactory().getDataSource(key, this.getProvider());
			if (ds == null) {
				ExceptionUtils.throwSystemException("当前 routingKey = " + key + " 对应的 dataSource 值为 null");
			}
			this.addDataSourceDestroy(ds);
			return ds;
		});
	}

}
